
package com.lucas.springboot_restful_api.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

public class CommonUtil {

    @Value("${md5.key:Lucas}")
    private static String md5Key;

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static String md5Encrypt(String text) throws Exception {
        return DigestUtils.md5Hex(text + md5Key);
    }

    public static String md5Encrypt(String text, String key) throws Exception {
        return DigestUtils.md5Hex(text + key);
    }

    public static boolean md5Verify(String text, String md5) throws Exception {
        String md5Text = md5Encrypt(text);
        return md5Text.equalsIgnoreCase(md5);
    }

    public static boolean md5Verify(String text, String key, String md5) throws Exception {
        String md5Text = md5Encrypt(text, key);
        return md5Text.equalsIgnoreCase(md5);
    }

    public static String makeUUID() {
        return UUID.randomUUID()
                .toString().replaceAll("-", "");
    }

    public static Long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

}
